package com.example.aigc_education.integration.impl;


import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.example.aigc_education.integration.AliOssIntegration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

/**
 * 阿里云第三方接口实现
 */
@Service
@Slf4j
public class AliOssIntegrationImpl implements AliOssIntegration {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.access-key-id}")
    private String accessKeyId;

    @Value("${aliyun.oss.access-key-secret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucket-name}")
    private String bucketName;


    @Override
    public String ossUpload(String objectName, byte[] bytes) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
        } catch (OSSException oe) {
            log.error("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason."+ "\n"
                    + "Error Message:" + oe.getErrorMessage()+ "\n"
                    +"Error Code:" + oe.getErrorCode()+ "\n"
                    +"Request ID:" + oe.getRequestId()+ "\n"
                    +"Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            log.error("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network."+ "\n"
                    + "Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        //阿里云oss中文件访问路径规则 https://BucketName.Endpoint/ObjectName
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(objectName);

        log.info("文件上传到:{}", stringBuilder.toString());
        //返回图片存储路径
        return stringBuilder.toString();
    }



    /**
     * 从阿里云下载文件到本地
     *
     * @param objectName 阿里云对象存储的文件的名字
     * @return 下载文件对象
     */
    @Override
    public OSSObject ossDownload(String objectName){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 下载Object到本地文件，并保存到指定的本地路径中。如果指定的本地文件存在会覆盖，不存在则新建。
            // 如果未指定本地路径，则下载后的文件默认保存到示例程序所属项目对应本地路径中。
            return ossClient.getObject(bucketName, objectName);
//            ossClient.getObject(new GetObjectRequest(bucketName, filename).
//                            <GetObjectRequest>withProgressListener(new OSSUploadFileUtils()),
//                    new File(filePath));
        } catch (OSSException oe) {
            log.error("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason."+ "\n"
                    + "Error Message:" + oe.getErrorMessage()+ "\n"
                    +"Error Code:" + oe.getErrorCode()+ "\n"
                    +"Request ID:" + oe.getRequestId()+ "\n"
                    +"Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            log.error("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network."+ "\n"
                    + "Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }


    /**
     * 删除云端文件
     * @param objectName  要删除的文件名字
     */
    @Override
    public void ossDelete(String objectName){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(bucketName, objectName);
        } catch (OSSException oe) {
            log.error("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason."+ "\n"
                    + "Error Message:" + oe.getErrorMessage()+ "\n"
                    +"Error Code:" + oe.getErrorCode()+ "\n"
                    +"Request ID:" + oe.getRequestId()+ "\n"
                    +"Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            log.error("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network."+ "\n"
                    + "Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }


}
